<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="SearchForm.KeyWord"
        style="width:250px"
        placeholder="可用 菜系名称 查询"
        class="filter-item"
      ></el-input>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        >查询</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleAdd"
        >添加</el-button
      >
    </div>
    <el-table
      :data="DataList"
      border
      fit
      highlight-current-row
      v-loading="listLoading"
      style="width: 100%"
    >
      <el-table-column prop="Name" label="菜谱名称" align="center" width="300">
      </el-table-column>
      <el-table-column prop="Info" label="菜谱内容" align="center" width="180">
      </el-table-column>
      <el-table-column
        prop="CoverPic"
        label="菜谱封面图"
        align="center"
        width="180"
      >
         <template slot-scope="scope">
           <div>
             <img :src="scope.row.CoverPic" width="75px" height="75px" alt="">
           </div>
        </template>
      </el-table-column>
      <el-table-column prop="CreateTimeStr" align="center" label="创建时间">
      </el-table-column>
      <el-table-column prop="Tags" align="center" label="菜谱标签">
      </el-table-column>
      <el-table-column align="center" width="200" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
            删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="TotalCount > 0"
      :total="TotalCount"
      :page.sync="SearchForm.pageIndex"
      :limit.sync="SearchForm.pageSize"
      @pagination="getList"
    />
    <!-- 编辑新增弹出框 -->
    <el-dialog
      :title="form.Id == 0 ? '新增菜谱' : '编辑菜谱'"
      :visible.sync="AddOrEditdialogVisible"
      width="30%"
      @close="handleClose"
    >
      <div>
        <el-form ref="form" :model="form" :rules="rule" label-width="80px">
          <el-form-item label="菜谱名称" prop="Name">
            <el-input v-model="form.Name"></el-input>
          </el-form-item>
          <el-form-item label="简单介绍" prop="Info">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              v-model="form.Info"
              placeholder=""
            ></el-input>
          </el-form-item>
          <el-form-item label="菜谱标签">
            <el-tag
              v-for="tag in AllTags"
              :key="tag"
              closable
              @close="handleTagClose(tag)"
              type="info"
            >
              {{ tag }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="tagVisible"
              v-model="inputTag"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput"
              >+ 新增</el-button
            >
          </el-form-item>
          <el-form-item label="菜谱封面" prop="CoverPic">
            <el-upload
              class="avatar-uploader"
              action="http://api.yohao.xyz/api/upload/UpLoadFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.CoverPic" :src="form.CoverPic" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="菜谱链接" prop="Url">
            <el-input v-model="form.Url" placeholder="暂定为下厨房的链接"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="AddOrEditdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import req from "@/utils/req";
import Pagination from "@/components/Pagination";
export default {
  components: { Pagination },
  data() {
    var checkUrl = (rule, value, callback) => {
       var reg=/^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/;
      if (value === "") {
        callback(new Error("请输入链接"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入正确的链接!"));
      } else {
        callback();
      }
    };
    return {
      SearchForm: {
        KeyWord: "",
        pageIndex: 1,
        pageSize: 20
      },
      form: {
        Id: 0,
        Name: "",
        CoverPic: "",
        Url: "",
        Info: "",
        Tags: ""
      },
      AllTags: [],
      TotalCount: 0,
      DataList: [],
      RoleList: [],
      AddOrEditdialogVisible: false, //
      listLoading: false,
      tagVisible: false,
      inputTag: "",
      //验证
      rule: {
        Name: [{ required: true, message: "请输入菜谱名称", trigger: "blur" }],
        CoverPic: [{ required: true, message: "请添加封面图", trigger: "blur" }],
        Url: [{ required: true, message: "请输入链接", trigger: "blur" },
        { validator: checkUrl, trigger: "blur" }
        ],
      },
      //设置权限菜单的字段
      IsTreedialogVisible: false
    };
  },
  watch: {},
  created() {
    this.getList();
  },
  methods: {
    handleFilter() {
      this.SearchForm.pageIndex = 1;
      this.getList();
    },
    getList() {
      this.listLoading = true;
      req.get("sys/Menu/pagelist", this.SearchForm).then(res => {
        this.DataList = res.Data.List;
        this.TotalCount = res.Data.TotalCount;
        setTimeout(() => {
          this.listLoading = false;
        }, 500);
      });
    },
    handleAvatarSuccess(res, file) {
      this.form.CoverPic = res.Data;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 4;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 4MB!");
      }
      return isLt2M;
    },
    //新增
    handleAdd() {
      this.AddOrEditdialogVisible = true;
    },
    handleUpdate(row) {
      this.form = Object.assign({}, row); // copy obj;
      this.AllTags= this.form.Tags.split(',')
      this.AddOrEditdialogVisible = true;
    },
    //关闭的回调
    handleClose(done) {
   
      this.form.Name = "";
      this.AllTags=[];
      this.form.CoverPic='';
      this.form.Tags='',
      this.form.Url ='';
      this.form.Info = "";
      this.form.Id = 0;
      this.$refs["form"].resetFields();
    },
    handleSubmit() {
      var url = this.form.Id == 0 ? "sys/Menu/Add" : "sys/Menu/Edit";
      this.form.Tags=this.AllTags.toString();
      this.$refs["form"].validate(valid => {
        if (valid) {
          req.post(url, this.form).then(res => {
            if (res.StatusCode === 200) {
              this.$notify.success({ title: "成功", message: "操作成功" });
              this.AddOrEditdialogVisible = false;
              this.getList();
            } else {
              this.$notify.error({ title: "失败", message: res.Data });
            }
          });
        }
      });
    },
    //删除
    handleDelete(row) {
      this.$confirm(`此操作将永久删除改菜谱 , 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          req.post("sys/Menu/Delete", row).then(res => {
            if (res.StatusCode === 200) {
              this.$notify.success({ title: "成功", message: "删除成功" });
              this.DataList = this.DataList.filter(el => {
                return el.ID != row.ID;
              });
            }
          });
        })
        .catch(() => {});
    },
    showInput() {
      this.tagVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputTag;
      if (inputValue) {
        if (this.AllTags.indexOf(inputValue) > -1) {
          this.$message({ type: "error", message: "该标签已存在" });
          return false;
        }
        this.AllTags.push(inputValue);
      }
      this.tagVisible = false;
      this.inputTag = "";
    },
    handleTagClose(tag) {
      this.AllTags.splice(this.AllTags.indexOf(tag), 1);
    }
  },
  watch: {
    AllTags: {
      handler: function(newval, oldval) {
        if (newval) {
          this.form.Tags = newval.toString();
        }
      },
      deep: true
    }
  }
};
</script>
<style >
.avatar-uploader div {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
